#!/bin/bash
# 用法: ./snapshot.sh <视频路径> [模式: single|s|tile|t] [数量] [tile行数] [tile列数] [--no-upload]
# 默认上传截图到 PixHost 图床，自动识别视频色彩空间（bt601/bt709/bt2020）

VIDEO="$1"
MODE="$2"
COUNT="$3"
TILEROW="$4"
TILECOL="$5"
NOUPLOAD="$6"
OUTDIR="."

# ========== 工具检测与安装 ==========
check_and_install() {
  local pkg=$1
  local cmd=$2
  if ! command -v "$cmd" >/dev/null 2>&1; then
    echo "缺少依赖: $pkg ($cmd)，尝试安装..."
    if command -v apt-get >/dev/null 2>&1; then
      sudo apt-get update && sudo apt-get install -y "$pkg"
    elif command -v yum >/dev/null 2>&1; then
      sudo yum install -y "$pkg"
    elif command -v dnf >/dev/null 2>&1; then
      sudo dnf install -y "$pkg"
    elif command -v pacman >/dev/null 2>&1; then
      sudo pacman -Sy --noconfirm "$pkg"
    else
      echo "无法自动安装 $pkg，请手动安装后再运行脚本。"
      exit 1
    fi
  fi
}

check_and_install "ffmpeg" "ffmpeg"
check_and_install "zip" "zip"
check_and_install "curl" "curl"
check_and_install "jq" "jq"
check_and_install "imagemagick" "convert"

# ========== 参数处理 ==========
if [ -z "$VIDEO" ]; then
  echo "用法: $0 <视频路径> [模式: single|s|tile|t] [数量] [tile行数] [tile列数] [--no-upload]"
  exit 1
fi

if [ -z "$MODE" ]; then MODE="single"; fi
if [[ "$MODE" == "s" ]]; then MODE="single"; fi
if [[ "$MODE" == "t" ]]; then MODE="tile"; fi

UPLOAD_ENABLED=true
if [[ "$NOUPLOAD" == "--no-upload" ]]; then UPLOAD_ENABLED=false; fi

# ========== 获取视频信息 ==========
DURATION=$(ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "$VIDEO")
DURATION=${DURATION%.*}
BASENAME=$(basename "$VIDEO")
BASENAME="${BASENAME%.*}"

# 自动识别色彩空间
COLORSPACE=$(ffprobe -v error -select_streams v:0 \
  -show_entries stream=color_space,color_transfer,color_primaries \
  -of default=noprint_wrappers=1:nokey=1 "$VIDEO" 2>/dev/null)

if echo "$COLORSPACE" | grep -iq "2020"; then
  COLOR_FILTER='format=yuvj420p,colorspace=bt2020:iall=bt2020:fast=1'
  COLOR_DESC="BT.2020（HDR/4K常见）"
elif echo "$COLORSPACE" | grep -iq "601\|smpte170m"; then
  COLOR_FILTER='format=yuvj420p,colorspace=bt601:iall=bt601:fast=1'
  COLOR_DESC="BT.601（标清视频）"
else
  COLOR_FILTER='format=yuvj420p,colorspace=bt709:iall=bt709:fast=1'
  COLOR_DESC="BT.709（高清/主流视频）"
fi

echo "检测到视频色彩空间: $COLOR_DESC"
echo "ffmpeg 滤镜参数: $COLOR_FILTER"
echo

URL_FILE="$OUTDIR/${BASENAME}_urls.txt"
BBCODE_FILE="$OUTDIR/${BASENAME}_bbcode.txt"
> "$URL_FILE"
> "$BBCODE_FILE"

# ========== 上传函数 ==========
upload_to_pixhost() {
  local img="$1"
  local json
  json=$(curl -s -X POST "https://api.pixhost.to/images" \
    -H 'Accept: application/json' \
    -F "img=@${img}" \
    -F 'content_type=0' \
    -F 'max_th_size=420')
  
  local show_url
  show_url=$(echo "$json" | jq -r '.show_url')

  if [[ "$show_url" == "null" || -z "$show_url" ]]; then
    echo "上传失败: $img"
    echo "返回: $json"
    return 1
  fi

  local img_url
  img_url=$(echo "$show_url" | sed -E 's#https://pixhost\.to/show/([0-9]+)/#https://img1.pixhost.to/images/\1/#')
  echo "$img_url"
}

# ========== 截图函数 ==========
take_snapshot() {
  local time=$1
  local index=$2
  local base=$3
  local jpg="$OUTDIR/${base}_snapshot_${index}.jpg"
  local png="$OUTDIR/${base}_snapshot_${index}.png"

  # ✅ 自动色彩空间修正
  ffmpeg -ss "$time" -i "$VIDEO" -frames:v 1 -q:v 2 \
    -vf "$COLOR_FILTER" \
    "$jpg" -y -loglevel quiet

  convert "$jpg" "$png"
  rm -f "$jpg"
  echo "生成截图: $png (时间点: ${time}s)"

  if [ "$UPLOAD_ENABLED" = true ]; then
    local url
    url=$(upload_to_pixhost "$png")
    if [ $? -eq 0 ]; then
      echo "上传成功: $url"
      echo "$url" >> "$URL_FILE"
      echo "[img]$url[/img]" >> "$BBCODE_FILE"
    fi
  fi
}

# ========== 处理 single 模式 ==========
if [ "$MODE" == "single" ]; then
  if [ -z "$COUNT" ]; then COUNT=6; fi
  for i in $(seq 1 $COUNT); do
    RAND=$(shuf -i 0-$((DURATION-1)) -n 1)
    take_snapshot "$RAND" "$i" "$BASENAME"
  done

# ========== 处理 tile 模式 ==========
elif [ "$MODE" == "tile" ]; then
  if [ -z "$COUNT" ]; then COUNT=16; fi
  if [ -z "$TILEROW" ]; then TILEROW=4; fi
  if [ -z "$TILECOL" ]; then TILECOL=4; fi

  TMPFILES=()
  INTERVAL=$((DURATION / COUNT))
  for i in $(seq 0 $((COUNT-1))); do
    START=$((i * INTERVAL))
    END=$(((i+1) * INTERVAL - 1))
    [ $END -lt $START ] && END=$START
    RAND=$(shuf -i $START-$END -n 1)
    TMP="$OUTDIR/tmp_$i.jpg"
    TMPFILES+=("$TMP")

    ffmpeg -ss "$RAND" -i "$VIDEO" -frames:v 1 -q:v 2 \
      -vf "$COLOR_FILTER" \
      "$TMP" -y -loglevel quiet
    echo "生成临时截图: $TMP (时间点: ${RAND}s)"
  done

  PREVIEW_JPG="$OUTDIR/${BASENAME}_preview.jpg"
  PREVIEW_PNG="$OUTDIR/${BASENAME}_preview.png"
  ffmpeg -pattern_type glob -i "$OUTDIR/tmp_*.jpg" \
    -filter_complex "tile=${TILECOL}x${TILEROW}" \
    -frames:v 1 "$PREVIEW_JPG" -y -loglevel quiet
  convert "$PREVIEW_JPG" "$PREVIEW_PNG"
  rm -f "${TMPFILES[@]}" "$PREVIEW_JPG"
  echo "生成拼图: $PREVIEW_PNG"

  if [ "$UPLOAD_ENABLED" = true ]; then
    url=$(upload_to_pixhost "$PREVIEW_PNG")
    if [ $? -eq 0 ]; then
      echo "上传成功: $url"
      echo "$url" >> "$URL_FILE"
      echo "[img]$url[/img]" >> "$BBCODE_FILE"
    fi
  fi
else
  echo "模式错误，只能是 single|s 或 tile|t"
  exit 1
fi

# ========== 汇总日志 ==========
if [ "$UPLOAD_ENABLED" = true ]; then
  echo
  echo "================ 上传完成汇总 ================"
  echo "直链 URL 文件: $URL_FILE"
  echo "BBCode 文件:   $BBCODE_FILE"
  echo "----------------------------------------------"
  echo "共上传 $(wc -l < "$URL_FILE") 张图片"
  echo

  echo "===== 直链 URL 列表 ====="
  cat "$URL_FILE"
  echo
  echo "===== BBCode 格式 ====="
  cat "$BBCODE_FILE"
  echo
else
  echo "已生成截图，但未上传 (--no-upload 模式)"
fi
